package com.gmrz.uap.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.gmrz.uap.cache.AmmsCacheUtil;
import com.gmrz.uap.cache.CacheStoreService;
import com.gmrz.uap.cache.CacheStoreServiceEhcacheImpl;
import com.gmrz.uap.cfg.SystemConst;
import com.gmrz.uap.model.User;
import com.gmrz.uap.uasconfig.UasConfigConst;
import com.gmrz.uap.uasconfig.UasConfigContentService;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.kit.StrKit;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class AuthInterceptor implements Interceptor {
    public void intercept(Invocation invocation) {

        HttpServletRequest request = invocation.getController().getRequest();
        HttpServletResponse response = invocation.getController().getResponse();
        Cookie cookie = UAPSSOHelper.findCookieByName(request, UAPSSOHelper.UAP_SESSION_ID);

        if (cookie != null) {

            CacheStoreService cacheStoreService = UAPSSOHelper.getCacheStoreServiceForSession();

            String ssoUser = cacheStoreService.getStr(cookie.getValue());

            if (StrKit.notBlank(ssoUser)) {//验证在缓存中是否已经保存用户信息
                User user = JSON.parseObject(ssoUser, new TypeReference<User>() {
                });

                request.setAttribute("sessionUser", user);
                //将缓存中的用户信息更新
                UAPSSOHelper.setUserIntoCache(request, user, UAPSSOHelper.UAP_SESSION_EXPIRE);
                invocation.invoke();

            } else {//如果缓存中没有用户信息，则跳转到登录页面

                //检查是否为异步请求，为空则为同步请求
                String requestType = request.getHeader("X-Requested-With");
                if (!StrKit.isBlank(requestType)) {
                    response.setHeader("sessionstatus", "timeout");
                    try {
                        response.sendError(518, "session timeout.");
                    } catch (IOException e) {
                    }

                    invocation.getController().render(ControllerSupport.responseJsonRender(null, invocation.getController().getRequest()));
                } else {
                    invocation.getController().redirect(SystemConst.LOGIN_PATH);
                }
            }
        } else {//如果在COOKIE中找不到UAPSESSONID则跳转到登录页面
            //检查是否为异步请求，为空则为同步请求
            String requestType = request.getHeader("X-Requested-With");
            if (!StrKit.isBlank(requestType)) {
                response.setHeader("sessionstatus", "timeout");
                try {
                    response.sendError(518, "session timeout.");
                } catch (IOException e) {
                }

                invocation.getController().render(ControllerSupport.responseJsonRender(null, invocation.getController().getRequest()));
            } else {
//                invocation.getController().redirect(SystemConst.LOGIN_PATH);
                invocation.getController().forwardAction(SystemConst.LOGIN_PATH);
            }
        }
    }
}
